# 创建时间：2025/5/3 星期六 13:51
# 创建人：李德才

import os


def menu():
    print('==============================学生信息管理系统==================================')
    print('--------------------------------------功能菜单----------------------------------')
    print('\t\t\t\t\t\t1.录入学生信息')
    print('\t\t\t\t\t\t2.查找学生信息')
    print('\t\t\t\t\t\t3.删除学生信息')
    print('\t\t\t\t\t\t4.修改学生信息')
    print('\t\t\t\t\t\t5.排序')
    print('\t\t\t\t\t\t6.统计学生总人数')
    print('\t\t\t\t\t\t7.显示所有学生信息')
    print('\t\t\t\t\t\t0.退出')
    print('---------------------------------------------------------------------------------')


def show_student_info():
    if os.path.exists('student.txt'):
        with open('student.txt', 'r', encoding='utf-8') as studentFile:
            student_list = studentFile.readlines()
            format_title = '{:^6}\t{:^8}\t{:^8}\t{:^8}'
            print(format_title.format('ID', '姓名', 'Python成绩', 'Java成绩'))
            for student in student_list:
                student = dict(eval(student))
                print(format_title.format(student.get('id'),  student.get('name'), student.get('python'), student.get('java')))
    else:
        print('文件不存在')
        return


def total_student():
    if os.path.exists('student.txt'):
        with open('student.txt', 'r', encoding='utf-8') as studentFile:
            student_list = studentFile.readlines()
            if student_list:
                print('一共有{}名学生'.format(len(student_list)))
            else:
                print('还没有录入学生信息')


def sort_student_info():
    if os.path.exists('student.txt'):
        with open('student.txt', 'r', encoding='utf-8') as studentFile:
            student_list = studentFile.readlines()
            student_new = []
            for item in student_list:
                student_new.append(dict(eval(item)))
            by = input('请输入排序的方式（1.按照ID升序，2.按照ID降序：')
            if by == '1':
                student_new = sorted(student_new, key=lambda student: student['id'])
            elif by == '2':
                student_new = sorted(student_new, key=lambda student: student['id'], reverse=True)
            for student in student_new:
                print(student)


def update_student_info():
    while True:
        if os.path.exists('student.txt'):
            new_student_list = []
            with open('student.txt', 'r', encoding='utf-8') as studentFile:
                student_list = studentFile.readlines()
                sid = input('请输入要修改的学生id：')
                name = input('请输入要修改的学生姓名：')
                java = input('请输入要修改的学生Java成绩：')
                python = input('请输入要修改的学生Python成绩：')
                for studentStr in student_list:
                    if not studentStr:
                        continue
                    student = dict(eval(studentStr))
                    if sid == student['id']:
                        student['name'] = name
                        student['java'] = java
                        student['python'] = python
                        new_student_list.append(student)
                    else:
                        new_student_list.append(student)
                with open('student.txt', 'w', encoding='utf-8') as studentFile:
                    for student in new_student_list:
                        studentFile.write(str(dict(student)) + "\n")
            answer = input('是否继续修改？y/n')
            if answer == 'y' or answer == 'Y':
                continue
            else:
                break
        else:
            print('文件不存在')
            return


def delete_student_info():
    while True:
        if os.path.exists('student.txt'):
            name = input('请输入要删除的学生姓名：')
            with open('student.txt', 'r', encoding='utf-8') as studentFile:
                student_list = studentFile.readlines()
                for studentStr in student_list:
                    student = dict(eval(studentStr))
                    if name == student['name']:
                        student_list.remove(studentStr)
                        with open('student.txt', 'w', encoding='utf-8') as studentFile:
                            for student in student_list:
                                studentFile.write(str(student) + "\n")
                        print('删除成功')
            answer = input('是否继续删除？y/n')
            if answer == 'y' or answer == 'Y':
                continue
            else:
                break
        else:
            print('文件不存在')
            return


def select_student_info():
    student_list = []
    while True:
        if os.path.exists('student.txt'):
            name = input('请输入要查找的学生姓名：')
            with open('student.txt', 'r', encoding='utf-8') as studentFile:
                student_list = studentFile.readlines()
                for student in student_list:
                    student = dict(eval(student))
                    if name == student['name']:
                        print(student)
                        break
                answer = input('是否继续查询？y/n')
                if answer == 'y' or answer == 'Y':
                    continue
                else:
                    break
        else:
            print('文件不存在')
            return


def insert_student_info():
    with open('student.txt', 'a', encoding='utf-8') as studentFile:
        while True:
            try:
                sid = input('请输入学生学号：')
                name = input('请输入学生姓名：')
                java = input('请输入学生Java成绩：')
                python = input('请输入学生Python成绩：')
            except  ValueError:
                print('输入的必须是数字')
            if sid and name and java and python:
                student = {"id": sid, "name": name, "java": java, "python": python}
                studentFile.write(str(student) + "\n")
                print('录入成功')
                answer = input('是否继续录入？y/n')
                if answer == 'y' or answer == 'Y':
                    continue
                else:
                    break
            else:
                print('输入不能为空')


def main():
    while True:
        menu()
        select = int(input("请选择"))
        if select in [0, 1, 2, 3, 4, 5, 6, 7]:
            if select == 0:
                answer = input('您确定要退出系统吗？y/n')
                if answer == 'y' or answer == 'Y':
                    print('谢谢您的使用')
                    break
                else:
                    continue
            elif select == 1:
                insert_student_info()
            elif select == 2:
                select_student_info()
            elif select == 3:
                delete_student_info()
            elif select == 4:
                update_student_info()
            elif select == 5:
                sort_student_info()
            elif select == 6:
                total_student()
            elif select == 7:
                show_student_info()
            else:
                print('您输入的选项有误，请重新输入')
        else:
            print('您输入的选项有误，请重新输入')


if __name__ == '__main__':
    main()
